package ru.mcfr.oxygen.util.web;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;

public class DocumentTypesGetter {
    // get from CMS list of common used xsd files
    // in format id, title, url

    //public Set<ItemInfo> schemas = null;

    public static Logger logger = Logger.getLogger(DocumentTypesGetter.class.getName());

    private AbstractWebConnector awc;

    public DocumentTypesGetter(Properties props) {
        awc = new AbstractWebConnector(props);
    }

    public Set<ItemInfo> getTypesFromURL(String sURL) {
        Set<ItemInfo> result = new TreeSet<ItemInfo>();

        String data = awc.getFromURL(sURL);

        Document XMLDoc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            XMLDoc = db.parse(new ByteArrayInputStream(data.getBytes("UTF-8")));

            NodeList types = XMLDoc.getElementsByTagName("type");
            for (int i = 0; i < types.getLength(); i++) {
                Element type = (Element) types.item(i);
                result.add(new ItemInfo(type.getAttribute("id"), type.getAttribute("title"),
                        type.getAttribute("noNamespaceSchemaLocation")));
                //schemas = result;
            }


        } catch (ParserConfigurationException e1) {
            logger.error(e1.getMessage());
        } catch (SAXException e1) {
            logger.error(e1.getMessage());
        } catch (IOException e1) {
            logger.error(e1.getMessage());
        } catch (NumberFormatException e1) {
            logger.error(e1.getMessage());
        } catch (Exception e1) {
            logger.error(e1.getMessage());
        }

        return result;
    }

}
